import com.alibaba.fastjson.JSONObject;
import com.vca.common.exception.VcaException;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class WeChatDemo {
    // 小程序的AppID和AppSecret
    private static final String APP_ID = "wxbd3b07b6a1ece617";
    private static final String APP_SECRET = "7a68c6cedbe84c2f149946ad9c59bd4e";
    // API请求地址
    private static final String API_URL = "https://api.weixin.qq.com/wxa/generatescheme";

    public static void main(String[] args) throws Exception {
        // 获取access_token
        String accessToken = getAccessToken(APP_ID, APP_SECRET);
        System.out.println("accessToken = " + accessToken);
        // 构建请求参数
        String query = "access_token=" + accessToken;
        String requestBody = "{\"jump_wxa\":{\"path\":\"pages/user-order-details/index\",\"query\":\"orderNo=order44892169389169181450897\"}}";
        System.out.println("requestBody = " + requestBody);
        // 发送API请求，获取URL Scheme链接
        String urlScheme = getURLScheme(API_URL, query, requestBody);
        JSONObject object = JSONObject.parseObject(urlScheme);
        if (!object.get("errmsg").equals("ok")) {
            throw new VcaException("生成URL Scheme失败");
        }
        String openlink = String.valueOf(object.get("openlink"));
        System.out.println("openlink = " + openlink);
    }

    /**
     * 获取access_token
     */
    private static String getAccessToken(String appId, String appSecret) throws IOException {
        String apiUrl = "https://api.weixin.qq.com/cgi-bin/token?" +
                "grant_type=client_credential&" +
                "appid=" + appId + "&" +
                "secret=" + appSecret;
        URL url = new URL(apiUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.connect();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
        String line = reader.readLine();
        reader.close();
        connection.disconnect();
        System.out.println("line = " + line);
        return String.valueOf(JSONObject.parseObject(line).get("access_token"));
    }

    /**
     * 发送API请求，获取URL Scheme链接
     */
    private static String getURLScheme(String apiUrl, String query, String requestBody) throws IOException {
        URL url = new URL(apiUrl + "?" + query);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.connect();
        connection.getOutputStream().write(requestBody.getBytes(StandardCharsets.UTF_8));
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        reader.close();
        connection.disconnect();
        return builder.toString();
    }
}
